const { UnauthenticatedError } = require('../errors');
const { isTokenValid } = require('../utils/jwt');

const authUser = async (req, res, next) => {
   const token = req.signedCookies.token;

   if (!token) {
      throw new UnauthenticatedError('Authentication Invalid');
   }

   try {
      const {
         payload: { username, userId },
      } = isTokenValid({ token });
      req.user = { username, userId };
      next();
   } catch (error) {
      throw new UnauthenticatedError('Authentication Invalid');
   }
};

const authSuper = async (req, res, next) => {
   const token = req.signedCookies.token;
   if (!token) {
      throw new UnauthenticatedError('Authentication Invalid');
   }

   try {
      const {
         payload: { username, userId, phone },
      } = isTokenValid({ token });

      if (phone !== '13421549190') {
         throw new UnauthenticatedError('Authentication Invalid');
      }
      req.user = { username, userId };
      next();
   } catch (error) {
      throw new UnauthenticatedError('Authentication Invalid');
   }
};

module.exports = {
   authUser,
   authSuper,
};
